from PIL import Image
import threading
import os, sys

def chars(x):
    return x

def main(a1, a3):
    # a1  *direPath*

    #v6 = os.getcwd()
    #os.chdir(a1)

    v1 = sorted(os.listdir(a1), key = chars)
    
    try:
        os.mkdir('crop.'+os.path.basename(a1))
    except:
        pass
    
    threads = []
    if sys.maxsize>2**32:
        for i1 in v1:
            if i1[-4:] in ['.jpg', 'jpeg', '.png', '.bmp']:
                threads.append(threading.Thread(target=d2_resize, args=(os.path.join(a1, i1), a3, os.path.join('crop.'+os.path.basename(a1), i1)) ))

        for t in threads:
            #while threads_count >= 10:
            #    sleep(randint(1,2)/100)
            t.start()
    else:
        for i1 in v1:
            d2_resize(os.path.join(a1, i1), a3, os.path.join('crop.'+os.path.basename(a1), i1))
    
    print("Saved in directory : "+'crop.'+os.path.basename(a1))
    
def d2_resize(a2, a3, a4):
    # a2  *filePath*
    # a3{ 4(w):3(h) }
    
    v2 = Image.open(a2)
    w, h = v2.size
    v3 = list(map(int, a3.split(':')))
    v1 = v3[1]*w - v3[0]*h
    
    if v1 > 0:
        v4 = int(v1/2/v3[1])
        v5 = v2.crop((v4, 0, w-v4, h))
    else:
        v4 = int(v1/2/v3[0])
        v5 = v2.crop((0, v4, w, h-v4))
    v5.save(a4, quality=100)

if __name__ == "__main__":
    if not len(sys.argv) <3:
        main(sys.argv[1].strip('\'\"\\').rstrip("/"), sys.argv[2])
    else:
        print("\tTo crop pictures,")
        print("\tUse the tool via:")
        print("\tpython [*this] [*path*] [*int*]:[*int*]")
        